import getpass,tkinter,tkinter.messagebox,tkinter.ttk
import os,requests
import time,re,webbrowser
import crawler_public,language_crawler_chs
from lxml import etree

username = getpass.getuser()
make_dir = 'C:\\Users\\' + username + '\\Documents\\DA_Tools\\'
crawler_path = make_dir + 'crawler_book_temp\\'
if not os.path.exists(crawler_path):
    os.makedirs(crawler_path)
# 发送小说指令标识
noval_name_number_send_path = crawler_path + 'noval_name_number_send_flag.log'
# 记录本地下载真实地址
zxcs_local_download_url_path = crawler_path + 'zxcs_local_download_url.log'
# 本地下载指令标识
local_download_path = crawler_path + 'local_download_flag.log'
# 记录网盘链接
noval_pan_link_path = crawler_path + 'noval_pan_link.log'
# 初始化语言对象
languages = language_crawler_chs.Language_Crawer()
languages_all = languages.all_languages_crawer()


def book_website_function(website_info_text,noval_name,noval_name_number,noval_name_entry_1,noval_name_number_send,
                       noval_name_number_send_disable,noval_pan_link_entry,noval_pan_pwd_entry,
                       noval_name_link,noval_name_pwd,noval_name_entry,
                       website_label,noval_name_label,noval_name_label_1,noval_pan_link_and_pwd_label,
                       noval_website_value,noval_pan_link_and_pwd_button,noval_pan_link_and_pwd_button_disable,
                       noval_pan_link_and_pwd_str,noval_local_download_button, noval_local_download_button_disable):
    # 知轩藏书网站主逻辑

    # 先禁用网盘链接提取码按钮和本地下载按钮
    try:
        local_download_flag = open(local_download_path, 'r').read()
        if local_download_flag == '1':
            noval_pan_link_and_pwd_button.place_forget()
            noval_local_download_button.place_forget()
            noval_pan_link_and_pwd_button_disable.place(x=5, y=215)
            noval_local_download_button_disable.place(x=150, y=215)
    except Exception:
        pass

    website_info_text.config(state='normal')
    website_info_text.delete('1.0',tkinter.END)
    website_label_orig_color = website_label.cget("background")  # 保持原始的背景色
    noval_name_label_orig_color = noval_name_label.cget("background")
    noval_pan_link_and_pwd_label.config(bg=website_label_orig_color)
    website_label.config(bg='yellow')
    website_info_text.insert(tkinter.END,'============================\n')
    website_info_text.insert(tkinter.END,f'欢迎下载 {noval_website_value} 所有精校版小说！\n')
    website_info_text.insert(tkinter.END,'============================\n')
    noval_name_entry.config(state='disable')
    noval_pan_link_entry.config(state='disable')
    noval_pan_pwd_entry.config(state='disable')
    noval_name_label.config(bg='yellow')
    website_info_text.insert(tkinter.END, f'你目前想要搜索的小说名称为：{noval_name}\n')
    website_info_text.insert(tkinter.END, '正在搜索中...（搜索速度取决于网络质量和网站服务）\n')
    website_info_text.config(state='disable')
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
    }
    if noval_website_value == languages_all['zxcs_book_name']:
        res = requests.get(f'https://www.zxcs.info/index.php?keyword={noval_name}', headers=header)
    res.encoding = res.apparent_encoding  # 防止乱码，自动转码
    res_html = res.text

    # 查找相关结果
    tree = etree.HTML(res_html)
    if noval_website_value == languages_all['zxcs_book_name']:
        tree_name = tree.xpath('//div[@id="pleft"]//dt/a/text()')
    website_info_text.config(state='normal')
    website_info_text.insert(tkinter.END, '努力搜索到如下结果：\n')
    book_name_list = []
    if tree_name:
        website_info_text.insert(tkinter.END, '---------------------------\n')
        for i, k in enumerate(tree_name):
            book_name_list.append(k)
            print(f'{i + 1} {k}')
            website_info_text.insert(tkinter.END,f'{i + 1} {k}\n')
        website_info_text.insert(tkinter.END, '---------------------------\n')

        website_label.config(bg=website_label_orig_color)
        noval_name_label.config(bg=noval_name_label_orig_color)
        noval_name_label_1_orig_color = noval_name_label_1.cget("background")
        noval_name_label_1.config(bg='yellow')
        website_info_text.insert(tkinter.END, '请在右侧输入你要下载的小说序号：\n')
        website_info_text.insert(tkinter.END, '温馨提示：你输入的序号必须是整数且不超过上述搜索出来的小说数量！\n')
        website_info_text.insert(tkinter.END, '正在等待接收您发送的小说序号...\n')
        website_info_text.see(tkinter.END)
        website_info_text.config(state='disable')

        noval_name_entry_1.config(state='normal')
        noval_name_number_send_disable.place_forget()
        noval_name_number_send.place(x=155, y=150)

        # 等待指令
        while True:
            number_send_flag = open(noval_name_number_send_path,'r').read()
            if number_send_flag.strip() == 'True':
                website_info_text.config(state='normal')
                try:
                    if noval_name_number.get() == 0:
                        website_info_text.insert(tkinter.END, '你输入的序号超出搜索范围，请重新输入！\n')
                        noval_name_entry.config(state='normal')
                        website_info_text.see(tkinter.END)
                        noval_name_label_1.config(bg=noval_name_label_1_orig_color)
                        noval_name_number_send_disable.place_forget()
                        noval_name_number_send.place(x=155, y=150)
                        with open(noval_name_number_send_path,'w') as fp:
                            fp.write('False')
                        continue
                    else:
                        noval_name_number = noval_name_number.get()
                        current_book_name = book_name_list[noval_name_number - 1]
                        website_info_text.insert(tkinter.END, '已成功接收到您发送的小说序号，正在进行下一步...\n')
                        website_info_text.insert(tkinter.END, f'你正在获取的小说是 {current_book_name}\n')
                        website_info_text.see(tkinter.END)
                except IndexError:
                    website_info_text.insert(tkinter.END, '你输入的序号超出搜索范围，请重新输入！\n')
                    noval_name_entry.config(state='normal')
                    website_info_text.see(tkinter.END)
                    noval_name_label_1.config(bg=noval_name_label_1_orig_color)
                    noval_name_number_send_disable.place_forget()
                    noval_name_number_send.place(x=155, y=150)
                    with open(noval_name_number_send_path, 'w') as fp:
                        fp.write('False')
                    continue
                noval_name_number_send.place_forget()
                noval_name_number_send_disable.place(x=155, y=150)
                noval_name_entry_1.config(state='disable')
                website_info_text.config(state='disable')
                break
            time.sleep(2)

        try:
            if noval_website_value == languages_all['zxcs_book_name']:
                tree_address = tree.xpath('//div[@id="pleft"]//dt/a/@href')[noval_name_number - 1]
            # 点击“下载小说”
            res_2 = requests.get(url=tree_address, headers=header)
            res_2.encoding = res_2.apparent_encoding  # 防止乱码，自动转码
            res2_html = res_2.text

            website_info_text.config(state='normal')
            noval_name_label_1.config(bg=noval_name_label_1_orig_color)
            noval_pan_link_and_pwd_label.config(bg='yellow')
            website_info_text.insert(tkinter.END, '正在获取小说的网盘下载链接及提取码...\n')
            website_info_text.see(tkinter.END)
            website_info_text.config(state='disable')

            # 进行网址处理
            tree = etree.HTML(res2_html)
            tree_main_url = tree_address.replace(tree_address.split('.')[-1],
                                                 tree_address.split('//')[-1].split('.')[-1].split('/')[0])
            if noval_website_value == languages_all['zxcs_book_name']:
                tree_address_2 = tree.xpath('//div[@class="fans-interact cf"]/a/@href')
            tree_address_new = tree_main_url + ''.join(tree_address_2)
            print(f'最终调试链接：{tree_address_new}')

            # 获取网盘下载链接及提取码
            res_3 = requests.get(url=tree_address_new, headers=header).text
            tree = etree.HTML(res_3)
            if noval_website_value == languages_all['zxcs_book_name']:
                tree_address_finally = tree.xpath('//span[@class="downfile"]/a/@href')
                tree_text_finally = tree.xpath('//span[@class="downfile"]/a/text()')
                tree_local_download = tree.xpath('//a[@class="localdown"]/@href')
            if not tree_local_download:
                print('不存在本地下载入口！')
                with open(local_download_path,'w') as fp:
                    fp.write('0')
                # 隐藏网盘链接和提取码点击按钮和本地下载按钮(避免重复渲染加载，先销毁原来再加载新的)
                try:
                    noval_pan_link_entry.place_forget()
                    noval_pan_pwd_entry.place_forget()
                    noval_pan_link_and_pwd_button_disable.place_forget()
                    noval_local_download_button_disable.place_forget()
                    noval_pan_link_and_pwd_button.place_forget()
                    noval_local_download_button.place_forget()
                except Exception:
                    pass
                # 显示网盘链接和提取码输入框
                noval_pan_link_entry.place(x=5,y=210)
                noval_pan_pwd_entry.place(x=5,y=240)
                if not tree_address_finally:
                    website_info_text.config(state='normal')
                    website_info_text.insert(tkinter.END,'找不到下载入口！原因：网盘链接丢失！\n')
                    noval_name_entry.config(state='normal')
                    website_info_text.config(state='disable')
                else:
                    website_info_text.config(state='normal')
                    website_info_text.insert(tkinter.END, '########################\n')
                    website_info_text.insert(tkinter.END,f'已成功获取到小说的网盘链接和提取码：\n{tree_address_finally[0]}\n{tree_text_finally[0]}\n')
                    website_info_text.insert(tkinter.END, '########################\n')
                    website_info_text.see(tkinter.END)
                    noval_name_entry.config(state='normal')
                    website_info_text.config(state='disable')
                    noval_pan_link_entry.config(state='normal')
                    noval_pan_pwd_entry.config(state='normal')
                    noval_name_link.set(tree_address_finally[0])
                    noval_name_pwd.set(tree_text_finally[0].split('：')[-1].replace(')',''))
            else:
                print('存在本地下载入口！')
                with open(local_download_path,'w') as fp:
                    fp.write('1')

                # 获取本地下载地址
                website_info_text.config(state='normal')
                zxcs_local_download(res_3,tree_main_url,header,website_info_text)
                # 隐藏网盘链接和提取码输入框
                try:
                    noval_pan_link_and_pwd_button_disable.place_forget()
                    noval_local_download_button_disable.place_forget()
                    noval_pan_link_entry.place_forget()
                    noval_pan_pwd_entry.place_forget()
                except Exception:
                    pass
                # 显示网盘链接和提取码点击按钮和本地下载按钮
                noval_pan_link_and_pwd_button.place(x=5,y=215)
                tree_text = tree_text_finally[0].split('：')[-1].replace(')', '')
                noval_pan_link_and_pwd_str.set(f'点击复制网盘链接地址\n提取码：{tree_text}')
                website_info_text.insert(tkinter.END,
                                         f'已成功获取到小说的网盘链接和提取码：\n{tree_address_finally[0]}\n{tree_text_finally[0]}\n')
                website_info_text.see(tkinter.END)
                website_info_text.config(state='disable')
                noval_local_download_button.place(x=150,y=215)
                noval_name_entry.config(state='normal')
                with open(noval_pan_link_path,'w') as fp:
                    fp.write(tree_address_finally[0])
        except Exception:
            website_info_text.insert(tkinter.END, '你输入的序号必须是整数且不超过上述搜索出来的小说数量！\n')
            noval_name_entry.config(state='normal')
            website_info_text.see(tkinter.END)
            noval_name_label_1.config(bg=noval_name_label_1_orig_color)
    else:
        website_info_text.insert(tkinter.END, '没有搜索到你想要的小说，可以重新搜索其他小说哦！\n')
        noval_name_entry.config(state='normal')
        website_info_text.see(tkinter.END)
        website_label.config(bg=website_label_orig_color)
        noval_name_label.config(bg=noval_name_label_orig_color)


def zxcs_local_download(res_html,zxcs_url,header,website_info_text):
    # 知轩藏书 本地下载
    """
    res_html 请求得到的网页内容
    zxcs_url 知轩藏书URL，本人已解析为 tree_main_url
    header 传递请求头，主要是User-Agent项
    website_info_text 信息输出框
    """
    # 获取真实下载地址Host
    local_download_host_re = re.findall('var url=(.*?);\n', res_html, re.S)
    local_download_host_1 = ''.join(local_download_host_re).replace('"', '')
    # 获取下面请求需要用到host
    local_download_host = zxcs_url
    # 获取完整的地址后面部分
    local_download_url_re = re.findall('url:(.*?),\n',res_html, re.S)
    local_download_url = ''.join(local_download_url_re).strip().replace("'", '')
    # 获取最终请求本地下载的url
    local_download_url_finally = local_download_host + local_download_url
    local_download_data_re = re.findall('data:(.*?),\n', res_html, re.S)[0].strip()
    local_download_data = re.findall('{(.*):(.*)}', local_download_data_re)
    # 请求本地下载真实url
    res = requests.post(url=local_download_url_finally, headers=header, data=local_download_data).text
    local_download_url_href = local_download_host_1 + res
    website_info_text.insert(tkinter.END,f'已成功获取真实本地下载URL：\n{local_download_url_href}\n')
    website_info_text.see(tkinter.END)
    # 记录本地下载真实地址
    with open(zxcs_local_download_url_path,'w') as fp:
        fp.write(local_download_url_href)




